package com.th.basemodel.base

import android.os.Bundle
import android.view.LayoutInflater
import androidx.lifecycle.Observer
import androidx.viewbinding.ViewBinding
import com.th.basemodel.bean.LoadAction
import com.th.basemodel.ext.toast
import com.th.basemodel.ui.LoadingDialogManager
import java.lang.reflect.ParameterizedType

abstract class BaseVB2Activity2<VB : ViewBinding> : AbsActivity() {

    private var _binding: VB? = null
    protected val mBinding: VB
        get() = requireNotNull(_binding) { "ViewBinding == null" }


    //反射创建ViewBinding
    open protected fun createViewBinding() {

        val clazz: Class<*> =
            (this.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<VB>

        try {
            _binding = clazz.getMethod(
                "inflate", LayoutInflater::class.java
            ).invoke(null, layoutInflater) as VB

        } catch (e: Exception) {
            e.printStackTrace()
            throw IllegalArgumentException("ViewBinding == null")
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        createViewBinding()
        super.onCreate(savedInstanceState)

        initDefaultLiveData()
    }

    private fun initDefaultLiveData() {
        getVm().mLoadActionLiveData.observe(this, Observer {
            when (it.action) {
                LoadAction.STATE_LOADING -> {
                    LoadingDialogManager.get().showLoading(this)
                }

                LoadAction.STATE_SUCCESS -> {
                    LoadingDialogManager.get().dismissLoading()
                }

                LoadAction.STATE_ERROR -> {
                    LoadingDialogManager.get().dismissLoading()
                    toast(it.message)
                }
            }
        })
    }

    abstract fun getVm(): BaseViewModel

    override fun setContentView() {
        setContentView(mBinding.root)
        setWindowPadding()
    }

    open fun setWindowPadding() {

    }

    override fun observeViewModel() {

    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
    }

}